"""
API上下文
把宿主能力（日志、配置、数据库、RPC等）注入插件
"""

import logging
from typing import Any, Dict, Optional, Callable


class APIContext:
    """
    API上下文对象
    
    提供宿主能力给插件使用：
    - 日志记录
    - 配置管理
    - 数据库访问
    - RPC调用
    - 自定义服务
    """
    
    def __init__(self, app_name: str = "PluginSystem") -> None:
        self.app_name = app_name
        self._logger = logging.getLogger(app_name)
        self._config: Dict[str, Any] = {}
        self._services: Dict[str, Any] = {}
        self._callbacks: Dict[str, Callable[..., Any]] = {}
    
    # ========== 日志能力 ==========
    
    def get_logger(self, plugin_name: str) -> logging.Logger:
        """
        获取插件专用日志记录器
        
        Args:
            plugin_name: 插件名称
            
        Returns:
            日志记录器
        """
        return logging.getLogger(f"{self.app_name}.{plugin_name}")
    
    def log(self, level: str, message: str, plugin_name: str = "") -> None:
        """
        记录日志
        
        Args:
            level: 日志级别（debug/info/warning/error/critical）
            message: 日志消息
            plugin_name: 插件名称
        """
        logger = self.get_logger(plugin_name) if plugin_name else self._logger
        getattr(logger, level.lower())(message)
    
    # ========== 配置能力 ==========
    
    def set_config(self, key: str, value: Any) -> None:
        """设置配置项"""
        self._config[key] = value
    
    def get_config(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        return self._config.get(key, default)
    
    def get_all_config(self) -> Dict[str, Any]:
        """获取所有配置"""
        return self._config.copy()
    
    # ========== 服务注册 ==========
    
    def register_service(self, name: str, service: Any) -> None:
        """
        注册服务
        
        Args:
            name: 服务名称
            service: 服务对象
        """
        self._services[name] = service
    
    def get_service(self, name: str) -> Optional[Any]:
        """
        获取服务
        
        Args:
            name: 服务名称
            
        Returns:
            服务对象，不存在返回None
        """
        return self._services.get(name)
    
    def unregister_service(self, name: str) -> None:
        """注销服务"""
        self._services.pop(name, None)
    
    # ========== 回调注册 ==========
    
    def register_callback(self, event: str, callback: Callable[..., Any]) -> None:
        """
        注册回调函数
        
        Args:
            event: 事件名称
            callback: 回调函数
        """
        self._callbacks[event] = callback
    
    def get_callback(self, event: str) -> Optional[Callable[..., Any]]:
        """获取回调函数"""
        return self._callbacks.get(event)
    
    def invoke_callback(self, event: str, *args: Any, **kwargs: Any) -> Any:
        """
        调用回调函数
        
        Args:
            event: 事件名称
            *args: 位置参数
            **kwargs: 关键字参数
            
        Returns:
            回调函数返回值
        """
        callback = self._callbacks.get(event)
        if callback:
            return callback(*args, **kwargs)
        return None
    
    # ========== 工具方法 ==========
    
    def create_child_context(self, plugin_name: str) -> 'APIContext':
        """
        创建子上下文（用于插件隔离）
        
        Args:
            plugin_name: 插件名称
            
        Returns:
            新的APIContext实例
        """
        child = APIContext(f"{self.app_name}.{plugin_name}")
        child._config = self._config.copy()
        child._services = self._services  # 共享服务
        return child
